package server

import (
	"context"
	"sync"

	"gitee.com/zawei/yggdrasil/pkg"
	"gitee.com/zawei/yggdrasil/pkg/log"
	"gitee.com/zawei/yggdrasil/pkg/metrics"
)

type Server interface {
	Init() error
	Start() error
	Stop() error
	GracefulStop(ctx context.Context) error
	Info() *Info
}

var (
	servers = make(map[string]Server, 0)
	mutex   = sync.Mutex{}
)

func RegisterServer(server Server) {
	mutex.Lock()
	defer mutex.Unlock()
	if _, ok := servers[server.Info().Scheme]; ok {
		log.Fatalf("duplicate scheme[%s]", server.Info().Scheme)
	}
	servers[server.Info().Scheme] = server
}

func GetServers() map[string]Server {
	mutex.Lock()
	defer mutex.Unlock()
	return servers
}

const (
	MetricsHandleTotal = "server_handle_total"
	MetricsHandleSec   = "server_handle_seconds"
)

func registerMetric() {
	err := metrics.CreateCounter(metrics.CounterOpts{
		Namespace: pkg.FrameworkName(),
		Subsystem: pkg.AppName(),
		Name:      MetricsHandleTotal,
		Labels:    []string{"type", "method", "peer", "code"},
	})
	if err != nil {
		log.Fatal(err)
	}

	err = metrics.CreateHistogram(metrics.HistogramOpts{
		Namespace: pkg.FrameworkName(),
		Subsystem: pkg.AppName(),
		Name:      MetricsHandleSec,
		Labels:    []string{"type", "method", "peer"},
	})
	if err != nil {
		log.Fatal(err)
	}
}

func Init() {
	registerMetric()
}
